﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuickJob.lib;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections;

namespace QuickJob.forms
{

    public partial class DropsBat : Form
    {

        public List<ListItemPicture> lListItemPictures = new List<ListItemPicture>();


        string Dir ;//= "C:\\Users\\Administrator\\Desktop\\临时文件";

        Config config;


        public DropsBat()
        {
            InitializeComponent();

            Dir = "C:\\Users\\Administrator\\Desktop\\临时文件";
            textBox_dropBatDir.Text = Dir;
            textBox_dropBatDir.DoubleClick += textBox_dropBatDir_DoubleClick;

        }
        public DropsBat(Config _config):this()
        {
            config = _config;

            ReloadConfig(config);
  
        }


        void textBox_dropBatDir_DoubleClick(object sender, EventArgs e)
        {
            FolderBrowserDialog dilog = new FolderBrowserDialog();
            dilog.Description = "请选择文件夹";
            if (dilog.ShowDialog() == DialogResult.OK)
            {
                Dir = dilog.SelectedPath;
                textBox_dropBatDir.Text = Dir;
            }
        }


        ///<summary>
        ///主要用于文件名的比较。
        ///</summary>
        public class FilesNameComparerClass : IComparer
        {
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            ///<summary>
            ///比较两个字符串，如果含用数字，则数字按数字的大小来比较。
            ///</summary>
            ///<param name="x"></param>
            ///<param name="y"></param>
            ///<returns></returns>
            int IComparer.Compare(Object x, Object y)
            {
                if (x == null || y == null)
                    throw new ArgumentException("Parameters can't be null");
                string fileA = x as string;
                string fileB = y as string;
                char[] arr1 = fileA.ToCharArray();
                char[] arr2 = fileB.ToCharArray();
                int i = 0, j = 0;
                while (i < arr1.Length && j < arr2.Length)
                {
                    if (char.IsDigit(arr1[i]) && char.IsDigit(arr2[j]))
                    {
                        string s1 = "", s2 = "";
                        while (i < arr1.Length && char.IsDigit(arr1[i]))
                        {
                            s1 += arr1[i];
                            i++;
                        }
                        while (j < arr2.Length && char.IsDigit(arr2[j]))
                        {
                            s2 += arr2[j];
                            j++;
                        }
                        if (int.Parse(s1) > int.Parse(s2))
                        {
                            return 1;
                        }
                        if (int.Parse(s1) < int.Parse(s2))
                        {
                            return -1;
                        }
                    }
                    else
                    {
                        if (arr1[i] > arr2[j])
                        {
                            return 1;
                        }
                        if (arr1[i] < arr2[j])
                        {
                            return -1;
                        }
                        i++;
                        j++;
                    }
                }
                if (arr1.Length == arr2.Length)
                {
                    return 0;
                }
                else
                {
                    return arr1.Length > arr2.Length ? 1 : -1;
                }
                //            return string.Compare( fileA, fileB );
                //            return( (new CaseInsensitiveComparer()).Compare( y, x ) );
            }
        }


        private void 加载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try {
                if (System.IO.Directory.Exists(textBox_dropBatDir.Text) == true)
                {


                    string[] dirs = System.IO.Directory.GetDirectories(textBox_dropBatDir.Text);
                    if(dirs == null || dirs.Length <= 0){
                        MessageBox.Show("没有文件夹可以加载");
                        return;
                    }


                    ArrayList lfolders = new ArrayList();
                    for (int i = 0; i < dirs.Length; i++) { lfolders.Add(dirs[i]); }

                    FilesNameComparerClass fileNameComparer = new FilesNameComparerClass();
                    lfolders.Sort(fileNameComparer);

                    List<string> listErr = new List<string>();
                    Point p = new Point(1, 1);
                    for (int i = 0; i < dirs.Length; i++)
                    {  
                        try
                        {
                            ListItemPicture item = new ListItemPicture(lfolders[i].ToString(), config);
                            lListItemPictures.Add(item);
                            this.flowLayoutPanel1.Controls.Add(item);
                            item.Location = p;
                            p.Y += item.Height;
                        }
                        catch {

                            listErr.Add(lfolders[i].ToString());
                        
                        }

                    }


                    if(listErr.Count!=0){
                        string errstring = "";
                        foreach(string s in listErr){errstring += s +"\r\n";}
                        MessageBox.Show("无法解析文件夹:"+"\r\n"+errstring);
                    }

                }
                else {
                    MessageBox.Show("文件夹无效");
                }
            }catch{}
        }
        private void 清除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lListItemPictures.Clear();
            this.flowLayoutPanel1.Controls.Clear();
        }



        /// <summary>
        /// 重新加载配置
        /// </summary>
        /// <param name="c"></param>
        private void ReloadConfig(Config c)
        { 
            //刷新下拉
            try
            {
                int index = this.comboBox_BatPingMing.SelectedIndex;
                this.comboBox_BatPingMing.Items.Clear();
                foreach (DropConfigItem i in config.clist)
                {
                    comboBox_BatPingMing.Items.Add(i.ConfigName);
                }
                comboBox_BatPingMing.SelectedIndex = index;

                foreach (ListItemPicture lip in lListItemPictures) {
                    lip.ReLoadConfig(config);
                }

            }
            catch { }        
        }


        /// <summary>
        /// 刷新，重新加载配置表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            ReloadConfig(config);

        }


        /// <summary>
        /// 应用　品名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                int index = this.comboBox_BatPingMing.SelectedIndex;
                if (index < 0) return;
                foreach (ListItemPicture lip in lListItemPictures)
                {
                    if (lip.Checked() == true) lip.SetConfig(index);
                }
            }
            catch { }
        }

        /// <summary>
        /// 排序　款号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string kuanhao = textBox_KuanHao.Text;
                Regex re = new Regex("[0-9]+(?=[^0-9]*$)");
                string numberString = re.Match(kuanhao).Value;
                string preString = kuanhao.Substring(0, kuanhao.Length - numberString.Length);
                int StartNumber = int.Parse(numberString);
                string stringFomat = preString + "{0:D" + numberString.Length + "}";

                for (int i = 0; i < lListItemPictures.Count; i++) {

                    ListItemPicture lip = lListItemPictures[i];
                    if (lip.Checked() == true) {
                        String KuanHao = string.Format(stringFomat, StartNumber);
                        lip.SetKuanHao(KuanHao);
                        StartNumber++;
                    }
                }

            
                
            }
            catch { }
        }

        private void button_createDrop_Click(object sender, EventArgs e)
        {
            try {
                progressBar1.Maximum = lListItemPictures.Count;
                progressBar1.Value = 0;
                foreach (ListItemPicture lip in lListItemPictures) {
                    if (lip.Checked())
                    {
                        //lip.SaveImage();
                        lip.SaveImageExt();
                    }
                    progressBar1.Value++;
                }
            }
            catch { }
        }

        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListItemPicture lip in lListItemPictures) { lip.SetChecked(true); }
        }

        private void 全不选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListItemPicture lip in lListItemPictures) { lip.SetChecked(false); }
        }

        private void 预加载品名ToolStripMenuItem_Click(object sender, EventArgs e)
        {  
            if(lListItemPictures.Count<=0)return;
            try{
                foreach(ListItemPicture lip in lListItemPictures)
                {
                    string pin = htmlOper.HtmlGetPinMingFromDocumentation(lip.imgDir);
                    lip.SetPinMing(pin);
                }
            }catch{}
        }


    }
}
